package com.lxk.concurrency.example.sync;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SynchronizedExample2 {

	// 修饰一个类
	// 作用于所有对象，即同一时刻，只能被一个线程执行
	public static void test1(int j) {
		synchronized (SynchronizedExample2.class) {
			for (int i = 0; i < 10; i++) {
				System.out.println("test1:" + i + " ---> " + j);
			}
		}
	}

	// 修饰一个静态方法
	// 作用于所有对象，即同一时刻，只能被一个线程执行
	public static synchronized void test2(int j) {
		for (int i = 0; i < 10; i++) {
			System.out.println("test2:" + i + " ---> " + j);
		}
	}

	public static void main(String[] args) {
		SynchronizedExample2 example1 = new SynchronizedExample2();
		SynchronizedExample2 example2 = new SynchronizedExample2();

		// 声明一个线程池，实现异步执行，即同时执行两个线程
		ExecutorService executorService = Executors.newCachedThreadPool();

		executorService.execute(() -> {
			example1.test1(1);
		});

		executorService.execute(() -> {
			example2.test1(2);
		});
	}
}
